package com.tools.common.object.json.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.tools.common.object.Note;
import com.tools.common.object.ObjKit;
import com.tools.web.interceptor.auth._common.SingleAuthUser;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Note("AuthUser 对象的序列号和反序列化类型处理器")
public class AuthUserTypeHandler {

    private AuthUserTypeHandler() {}


    @Note("用户单在线记录 SingleAuthUser 对象的序列化逻辑")
    public static JsonSerializer<SingleAuthUser> singleAuthUserSerializer() {
        return new JsonSerializer<SingleAuthUser>() {
            @Override
            public void serialize(SingleAuthUser singleAuthUser, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeStartObject();
                private_writeBaseFields(singleAuthUser, jsonGenerator);
                jsonGenerator.writeEndObject();
            }
        };
    }



    @Note("将基本的属性写入进去")
    private static void private_writeBaseFields(SingleAuthUser singleAuthUser, JsonGenerator jsonGenerator) throws IOException {
        String uuid = singleAuthUser.getUuid();
        if(uuid != null && !uuid.isEmpty()) jsonGenerator.writeStringField("uuid", uuid);
        jsonGenerator.writeObjectField("userId", singleAuthUser.getUserId());
        String loginDeviceType = singleAuthUser.getLoginDeviceType();
        if(loginDeviceType != null && !loginDeviceType.isEmpty()) jsonGenerator.writeStringField("loginDeviceType", loginDeviceType);
        String loginUserType = singleAuthUser.getLoginUserType();
        if(loginUserType != null && !loginUserType.isEmpty()) jsonGenerator.writeStringField("loginUserType", loginUserType);
        Object user = singleAuthUser.getUser();
        if(user != null) jsonGenerator.writeObjectField("user", user);
        Class<?> userTypeClass = singleAuthUser.getUserTypeClass();
        if(userTypeClass != null) jsonGenerator.writeStringField("userTypeClass", userTypeClass.getName());
        Map<String, ?> roleKeyMap = singleAuthUser.getRoleKeyMap();
        if(roleKeyMap != null) jsonGenerator.writeObjectField("roleKeyMap", roleKeyMap);
        Map<String, ?> permKeyMap = singleAuthUser.getPermKeyMap();
        if(permKeyMap != null) jsonGenerator.writeObjectField("permKeyMap", permKeyMap);
        List<?> routerList = singleAuthUser.getRouterList();
        if(routerList != null) jsonGenerator.writeObjectField("routerList", routerList);
        Map<String, Object> customData = (Map<String, Object>) ObjKit.getFieldValue(singleAuthUser, "customData");
        if(customData != null && !customData.isEmpty()) jsonGenerator.writeObjectField("customData", customData);
    }

}
